<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示信息区域 -->
      <el-alert title="添加商品信息" type="info" :closable="false" center show-icon> </el-alert>

      <!-- 步骤条区域  active激活的步骤 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs标签页 el-tab-pane只能作为el-tab的子元素 
      所以form表单要放在最外面 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top" label-width="100px">
        <el-tabs v-model="activeIndex" @tab-click="handleTabClick" tab-position="left" :before-leave="beforeTabsLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 商品分类级联选择框 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                clearable
                v-model="addForm.goods_cat"
                :options="classifyList"
                :props="classifyProps"
                @change="classifyChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="value in manyParamasList" :key="value.attr_id" :label="value.attr_name">
              <el-checkbox-group v-model="value.attr_vals">
                <el-checkbox border :label="value1" :key="index1" v-for="(value1, index1) in value.attr_vals"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="value in onlyParamasList" :key="value.attr_id" :label="value.attr_name">
              <el-input v-model="value.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片要上传到的图片后台api地址 
            on-preview	点击文件列表中已上传的文件时的钩子 
            on-remove	文件列表移除文件时的钩子
            list-type   预览组件的呈现方式
            headers	    设置上传的请求头部 如果不设置headers 则请求失败 因为是无效token
            on-success	文件上传成功时的钩子-->
            <el-upload
              :on-success="fileSuccess"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor ref="quillEditorRef" v-model="addForm.goods_introduce"> </quill-editor>
            <el-button @click="addGoods" class="addbtn" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" alt="" class="preview" />
    </el-dialog>
  </div>
</template>

<script>
//引入lodash深拷贝
import _ from 'lodash'
export default {
  data() {
    return {
      //被激活的标签页的索引
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //级联选择框选中的分类的id [1, 4, 24]
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      classifyList: [],
      //级联选择框的配置信息
      classifyProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true, // 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。
        disabled: true
      },
      //动态参数列表
      manyParamasList: [],
      //静态属性列表
      onlyParamasList: [],
      //上传图片的url地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //预览图片时的url
      previewUrl: '',
      //控制图片预览对话框的显示与隐藏
      previewDialogVisible: false
    }
  },
  created() {
    this.getClassifyList()
  },
  methods: {
    async getClassifyList() {
      const { data: response } = await this.$axios.get('categories')
      if (response.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.classifyList = response.data
      //   console.log(response.data)
      return this.$message.success(response.meta.msg)
    },
    //分类选项发生变化时触发
    async classifyChange() {
      //console.log(this.addForm.goods_cat)
      //只能选择三级分类 若不是 则清空选择的分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    //标签页发生变化时触发
    //activeName即将进入的标签页 oldActiveName即将离开的标签页
    beforeTabsLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false //阻止标签页切换
      }
    },
    // tab 被选中时触发
    async handleTabClick() {
      //证明被选中的是商品参数面板 发送请求获取动态参数
      if (this.activeIndex === '1') {
        //获取参数列表
        const { data: response } = await this.$axios.get('categories/' + this.classifyId + '/attributes', {
          params: {
            sel: 'many'
          }
        })
        // console.log(response)
        if (response.meta.status !== 200) return this.$message.error('获取分类参数失败')
        response.data.forEach(item => {
          //先判断item.attr_vals是否存在
          //若存在再分割字符串 否则返回空数组 防止出现空标签
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyParamasList = response.data
        this.$message.success('获取动态参数成功')
      } else if (this.activeIndex === '2') {
        //证明被选中的是商品属性面板 发送请求获取静态属性
        //获取静态属性列表
        const { data: response } = await this.$axios.get('categories/' + this.classifyId + '/attributes', {
          params: {
            sel: 'only'
          }
        })
        // console.log(response)
        if (response.meta.status !== 200) return this.$message.error('获取商品属性失败')

        this.onlyParamasList = response.data
        this.$message.success('获取商品属性成功')
      }
    },
    //点击图片预览时触发
    handlePreview(file) {
      //   console.log(file)
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    //  移除图片时触发
    handleRemove(file) {
      //   console.log(file)
      //   获取要删除的图片的临时路径
      const filepath = file.response.data.tmp_path
      //   从addForm.pics数组中找到这个图片对应的索引值
      const index = this.addForm.pics.findIndex(item => item.pic === filepath)
      //   将图片信息从数组中删除
      this.addForm.pics.splice(index, 1)
      //   console.log(this.addForm)
    },
    // 文件上传成功时触发
    fileSuccess(response) {
      //   console.log(response)
      //因为接口中是对象的形式 所以先拼接成一个图片对象
      const picInfo = { pic: response.data.tmp_path }
      // 再push到数组中
      this.addForm.pics.push(picInfo)
      //   console.log(this.addForm)
    },
    // 添加商品处理函数
    addGoods() {
      //   console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) {
          return this.$message.error('请完整填写表单')
        }

        // 因为要把goods_cat转换成字符串 但是级联选择器只能使用数组 会报错
        // 所以使用深拷贝将addForm深拷贝一份 将新得到的数据作为请求参数
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // attrs 商品的参数（数组），包含动态参数 和 静态属性
        // 所以要拼接manyParamasList和onlyParamasList
        // 处理动态参数 动态参数的attr_vals是数组 所以要转换为字符串
        this.manyParamasList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join('')
          }
          // 再push到数组中
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyParamasList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          // 再push到数组中
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // console.log(form)

        const { data: response } = await this.$axios.post('/goods', form)
        // console.log(response)
        if (response.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    //处理参数id
    classifyId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 25px 0;
}
.el-checkbox {
  margin: 0 15px 15px 0 !important;
}
.preview {
  width: 100%;
}
.addbtn {
  margin-top: 20px;
}
// .el-steps {
//   display: flex;
//   justify-content: center;
// }
</style>
